var ws;
var tryonce = false;
var connected = false;
var server_addr = "ws://127.0.0.1:18888";//本机端口地址
var msg_handler = {};
var orgwidth = 0;
var orgheight = 0;

var resetx = 20;
var resety = 20;
var resetwidth = 300;
var resetheight = 400;

var iswaiting = false;

// 使用JSON  向服务发送的操作命令
const CLT_MSG = {
    // 打开相机 cap:相机ID
    BEGIN_CAP : 1,
    // 关闭相机 cap:相机ID
    STOP_CAP : 2,
    // 获取PID
    GET_PID :3,
    // 获取分辨率
    GET_FBL : 4,
    //设置分辨率
    SET_FBL : 5,
    //设置MJPG格式
    SET_MJPG: 6,
    //设置视频旋转
    SET_TURN: 7,
    //设置视频截图保存的jpg质量
    SET_QUALITY:8,
    //设置自动裁边
    SET_AUTOCROP:9,
    //设置预设框选
    SET_PREST:10,
    //获取当前预设框选
    GET_PREST_INFO:11,
    //视频格式弹窗
    FORMAT_DLG:12,
    //视频属性弹窗
    PROPERTY_DLG:13,
    //设置截图颜色模式 彩色 黑白 灰度
    SET_COLOR_MODEL:14,
    //截图
    GET_PICTURE:15,
    //设置去底色参数
    SET_CLEAN_PARAM:16,
    //内存截图
    GET_PICTURE_MEM:17,
    //base64测试
    TEST_BASE64:18,
    //制作PDF的临时目录
    SET_TEMPDIR:19,
    //开始制作PDF
    BEGIN_PDF:20,
    //PDF截图 保存到PDF临时目录
    GET_PDF_PICTURES:21,
    //结束制作PDF
    END_PDF_PICTURES:22,
    //PDF文件转为文件里的BASE64码
    PDF_TO_BASE64:23,
    //文件里的BASE64码转为PDF文件
    BASE64_TO_PDF:24,
    //PDF文件转为BASE64字符串
    PDF_TO_BASE64_STR:25,
    //删除制作PDF的图片文件
    DEL_PICTURE_PDF:26,
    //打印图片
    PRINT_IMAGE:27,
    //设置显示错误弹窗
    SHOW_ERROR_BOX:28,
    //获取视频连接事件
    GET_EVENT:29,
    //预设框选鼠标消息
    PRESET_MOUSEDOWN:30,
    PRESET_MOUSEMOVE:31,
    PRESET_MOUSEUP:32,

    //多图裁剪
    MULTI_DETE:33,
    //人脸检测
    // FACE_DETE:34,
    //设置DPI
    SET_DPI:35,
    //版本信息
    LIB_INFO:36,

    IDCARD_COPY:37,
    CANCEL_IDCARD_COPY:38,

    //人证对比
    // FI_INIT:41,
    // IDCARD_COMPARE:40,
    // FI_UNIT:42,

    BEGIN_RECORD_VIDEO:43,
    STOP_RECORD_VIDEO:44,
    PAUSE_RECORD_VIDEO:45,

    BASE64_COMPARE:46,
    // DETECT_FACE:47,
    // STOP_DETECT_FACE:48,
    //读卡
    READ_IDCARD : 51,
    //水平
    HCOPY_IDCARD :54,

    SET_AUTOOFFSET:111,

    //http上传下载
    HTTP_UPLOAD:120,
    HTTP_DOWNLOAD:121,
    HTTP_GETPROGRESS:122,
    HTTP_GETRESULT:123,
    HTTP_CLOSE:124,
};

const SVR_BIN_MSG = {
    CAP_FRAME : 1, //后台帧消息
};

function onLoad(type){
    //页面load消息
    if(ws){return;}
    output("正在连接：" + server_addr);
    ws = new WebSocket(server_addr);
    ws.onopen = function(evt) {
        if(connected)		{ return;}
        connected = true;
        output("已经连接到服务器");
        if (type==0){
            cam_switch(1)
        }
    };
    ws.onclose = function(evt) {
        if(!connected) {
            if(!tryonce) {
                window.location.href = "FLShell://"
                setTimeout("onLoad()", 1000); //修改此处
                tryonce = true;
            } else {
                setTimeout("onLoad()", 1000);
            }
        } else {
            output("已断开服务器连接");
            connected = false;
        }
        ws = null;
    }

    ws.onmessage = function(evt) {
        if(evt.data.length === 0 ){
            return;
        }

        if(typeof evt.data === 'string'){
            var msg = JSON.parse(evt.data);
            if(msg.err && msg.err !== 0){
                output("错误 - " + msg.err + ", " + msg.msg);
            } else if(msg.msg){
                output(msg.msg);
            }

            if(msg.user_data){
                callback[msg.user_data](msg);
                if(typeof msg.user_data === 'number'){
                    callback[msg.user_data] = undefined;
                }
            }
        } else{
            var file = new FileReader();
            file.onload = function(evt) {
                if(evt.target.readyState == FileReader.DONE){
                    var data = new Uint8Array(evt.target.result);
                    if(data[0] == SVR_BIN_MSG.CAP_FRAME){
                        return drawImage(data);
                    }
                }
            };
            file.readAsArrayBuffer(evt.data);
        }
    }
    if (type==0) {
        var clicked = false;
        var canvas = document.getElementById("bigPriDev");
        canvas.onmousedown = function (e) {
            this.style.cursor = "crosshair";
            clicked = true;
            if (e.offsetX && e.offsetY) {
                sendMsg(CLT_MSG.PRESET_MOUSEDOWN, {origX: e.offsetX, origY: e.offsetY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            } else {
                sendMsg(CLT_MSG.PRESET_MOUSEDOWN, {origX: e.layerX, origY: e.layerY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            }
        }
        canvas.onmousemove = function (e) {
            if (!clicked) {
                this.style.cursor = "default";
                return;
            }
            this.style.cursor = "crosshair";

            if (e.offsetX && e.offsetY) {
                sendMsg(CLT_MSG.PRESET_MOUSEMOVE, {offx: e.offsetX, offy: e.offsetY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            } else {
                sendMsg(CLT_MSG.PRESET_MOUSEMOVE, {offx: e.layerX, offy: e.layerY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            }
        }
        canvas.onmouseup = function (e) {
            this.style.cursor = "default";
            if (!clicked) {
                return;
            }

            if (e.offsetX && e.offsetY) {
                sendMsg(CLT_MSG.PRESET_MOUSEUP, {offx: e.offsetX, offy: e.offsetY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            } else {
                sendMsg(CLT_MSG.PRESET_MOUSEUP, {offx: e.layerX, offy: e.layerY}, function (msg) {
                    if (msg.err !== 0) {
                        return;
                    }
                });
            }

            clicked = false;
        }
    }

}

var context = 1;
var callback = {}
//向后台发送消息的处理函数
function sendMsg(proto, msg, cb){
    if(!ws){return;}
    if(typeof msg !== 'object'){
        if(typeof msg === 'function') {cb = msg;msg = {};
        } else{msg = {}}
    }
    msg.proto = proto;
    if(typeof cb === 'function'){
        callback[++context] = cb;
        msg.user_data = context;
    }
    ws.send(JSON.stringify(msg));
}
//打印调试信息函数
function output(content) {
    console.log(content)
}

//读身份证getIcardData
function ReadIDCard(t,callbackid) {
    return sendMsg(CLT_MSG.READ_IDCARD, function(msg){
        if(msg.err == 155){layer.alert(msg.msg, { icon: 3 });}
        if(msg.err !== 0){ return;}
        output("单读卡");
       var  dataCard = {};
        dataCard.empName = msg.strName;
        if("男" == msg.strSex){
            dataCard.empSex = 1;
        }else{
            dataCard.empSex = 2;
        }
        //身份证地址
        dataCard.empRegisteredPlace = msg.strAddress;
        //身份证号
        dataCard.empIndentity = msg.strID;
        //横向复印
        if (t==1) {
            sendMsg(CLT_MSG.HCOPY_IDCARD, {copy_path: "D:\\"}, function (msg) {
                console.log(msg)
                if (msg.err !== 0) {
                    return;
                }
                // document.getElementById("IDCardDisplay").src = "data:image/jpg;base64," + msg.hcopy;
                dataCard.fileBase64 = "data:image/jpg;base64," + msg.hcopy;
                output("横向复印" + msg.filename);
                callbackid(dataCard)
            })
        }else {
            callbackid(dataCard)
        }
    });
}
//检查视频帧时间戳
function checkTimestamp(svr_time) {
    var myDate = new Date();
    var clt_time = myDate.getSeconds() * 1000 + myDate.getMilliseconds();
    if(clt_time < svr_time){
        clt_time += 60 * 1000;
    }

    return clt_time - svr_time < 3000;
}

const base_offset = 3;
var orgdrawwidth = 0;
var orgdrawheight = 0;
//视频帧绘制函数
function drawImage(data) {
    // LE
    // 校验视频是否在一定时间内的
    if(!checkTimestamp(data[2] * 256 + data[1])){
        return;
    }
    //视频帧头有时间戳 注意偏移 和 大小端处理
    var width = data[base_offset + 1] * 256 + data[base_offset];
    var height = data[base_offset + 3] * 256 + data[base_offset + 2];

    var cam = document.getElementById('bigPriDev');
    var context = cam.getContext("2d");
    if(orgdrawwidth != width || orgdrawheight != height){
        orgdrawwidth = width;
        orgdrawheight = height
        cam.height = cam.height;
    }

    var image = context.createImageData(width, height);
    for(var n = 0; n != height; ++n){
        for(var m = 0; m != width; ++m)
        {
            var image_offset = ((height - n - 1) * width + m) * 4;
            var data_offset = (n * width + m) * 3 + base_offset + 4;
            image.data[image_offset] 			= data[data_offset + 2];
            image.data[image_offset + 1] 	= data[data_offset + 1];
            image.data[image_offset + 2] 	= data[data_offset];
            image.data[image_offset + 3] 	= 255;
        }
    }
    context.putImageData(image, 0, 0);
}
//打开视频
function cam_switch(capID) {
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.BEGIN_CAP, {cap : capID}, function(msg){
        if(msg.err !== 0){
            iswaiting = false;
            return output("打开视频失败");
        }
        orgwidth = msg.width;
        orgheight = msg.height;
        SetAutoCutOn();
        SetResolution();
        output("打开视频" + capID + "成功，width = " + msg.width + ",height =  " + msg.height);
        iswaiting = false;
    });
}


function bbase64(){     //内存截图
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.SET_QUALITY, {quality:50},function(msg){ //设置jpg质量
        if(msg.err !== 0) {
            iswaiting = false;
            return;
        }
        output("设置截图图片质量 : quality=" + 50);

        sendMsg(CLT_MSG.GET_PICTURE_MEM,{turn:0}, function(msg){
            if(msg.err !== 0){
                iswaiting = false;
                return;
            }
            var s = "data:image/jpg;base64," + msg.base64str;
            document.getElementById("Base64IMG").src= s;//网页预览图片
            document.getElementById("path_imgbase64").value= s;//网页预览图片
            output("base64 长度 : " + s.length);
            iswaiting = false;
        });
    });
};

function SetResolution(){
    if(iswaiting) return;
    iswaiting = true;
    var first = false;
    var second = false;
    sendMsg(CLT_MSG.SET_MJPG, {isMJPG:1},function(msg){   //设置MJPG格式
        if(msg.err !== 0) {
            first = true;
            if(first == true && second == true) iswaiting = false;
            return;}
        output("MJPG : " + 1);
        first = true;
        if(first == true && second == true) iswaiting = false;
    });
    sendMsg(CLT_MSG.SET_FBL, {width:800,height:600},function(msg){  //设置分辨率
        if(msg.err !== 0) {
            if(msg.err == 106)
                output("设置视频格式失败");
            second = true;
            if(first == true && second == true)
                iswaiting = false;
                return;
        }
        output("设置分辨率 : width=" + 800 + ",height=" + 600);
        second = true;
        if(first == true && second == true) iswaiting = false;
    });
};

function SetAutoCutOn(){  //设置自动裁边开启
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.SET_AUTOCROP, {open:1},function(msg){
        if(msg.err !== 0) {
            iswaiting = false;
            bAutoCut = false;
            return;}
        output("设置自动裁边 : open=" + 1);
        bAutoCut = true;
        iswaiting = false;
    });
};


function setBeginPDF() {
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.SET_TEMPDIR,{path:"E:\\tp\\temp"},function(msg){
        console.log(msg.err !== 0)
        if(msg.err !== 0){
            return;
        }else {
            sendMsg(CLT_MSG.BEGIN_PDF,function(msg){
                if(msg.err !== 0){
                    iswaiting = false;
                    return;
                }
                document.getElementById('container').innerHTML = "";
                document.getElementById('uploadprogress').value = "开始制作-PDF";
                output("开始制作PDF3");
                iswaiting = false;
            });
        }
        output("设置PDF路径2: " + "E:\\tp\\temp");
        iswaiting = false;
    });
}

//设置制作PDF临时目录
function SetPDFPath(){
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.SET_TEMPDIR,{path:"E:\\tp\\temp"},function(msg){
        if(msg.err !== 0){
            sendMsg(CLT_MSG.SET_TEMPDIR,{path:"E:\\tp\\temp"},function(msg){
                if(msg.err !== 0){
                    iswaiting = false;
                    return;}
                output("设置PDF路径: " + "E:\\tp\\temp");
                iswaiting = false;
            });
            return;
        }
        output("设置PDF路径: " + "E:\\tp\\temp");
        iswaiting = false;
    });
};

//PDF截图 保存到PDF临时目录
function GetPDF(){
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.GET_PDF_PICTURES,{turn:0},function(msg){
        if(msg.err !== 0){
            iswaiting = false;
            return;}
        // output("PDF 文件 : " + msg.path + ",PDF文件 BASE64码长度：" + msg.base64str.length);

        var imgFile =  "file:///" + msg.path;
        var imgPath = "data:image/jpg;base64,"+msg.base64str;

        document.getElementById("Base64IMG").src= imgPath;
        var container =document.getElementById('container');
        var newchild = document.createElement("div");
        newchild.setAttribute("style", "float:left");
        newchild.setAttribute("id", imgPath);

        newchild.innerHTML = "" +
            "<img  width='105' height='85' src='"+imgPath+"' onclick=' lookLayerImg(this)' style='padding-right: 10px;' /></img>" ;
        container.appendChild(newchild);
        // output("PDF 文件 : " + imgFile + ",PDF文件 BASE64码长度：" + imgPath );

        document.getElementById('uploadprogress').value = "正在拍照.....（内容错误重新点击“生成PDF开始，所有图片将清空”）";
        iswaiting = false;
    });
};
// 结束制作PDF
function EndPDF(){
    if(iswaiting) return;
    var contract_sn = document.getElementById('contract_sn').value;
    console.log(contract_sn)
    iswaiting = true;
    sendMsg(CLT_MSG.END_PDF_PICTURES,{path:"E:\\tp\\"+contract_sn+".pdf"},function(msg){
        if(msg.err !== 0){return;
        }else {
            sendMsg(CLT_MSG.PDF_TO_BASE64_STR,{file:"E:\\tp\\"+contract_sn+".pdf"},function(msg){
                if(msg.err !== 0){
                    iswaiting = false;
                    if(msg.err == 108){return output("读文件错误");}
                }
                document.getElementById('path_imgbase64').value='data:application/pdf;base64,'+msg.base64str

                document.getElementById('uploadprogress').value = "结束拍照，并已生成PDF文件，请点击上传";
                output("文件 BASE64 长度: " + msg.base64str.length);
                iswaiting = false;
            });
        }
        output("结束PDF PDF文件：" + "E:\\tp\\"+contract_sn+".pdf");
        iswaiting = false;
    });
};



function DelPDF1(thisdel){   //删除制作PDF的临时图片文件
    if(iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.DEL_PICTURE_PDF,{file:3},function(msg){
        if(msg.err !== 0){
            iswaiting = false;
            return;}
        output("删除PDF图片文件成功");
        iswaiting = false;
    });
    thisdel.parentNode.removeChild(thisdel.parentNode);
    // document.getElementById("IMG1").src= null;
};


var uploadId = 0;
var downloadId = 0;
var isuploadordownload = false;
var upprocess = 0;
var downprocess = 0;
var input_selector = '';
function start_progresstimer() {
    isuploadordownload = true;
    setTimeout("update_progress()", 100);
}

function stop_progresstimer() {
    isuploadordownload = false;
}

function update_progress()
{
    if(!isuploadordownload){
        document.getElementById('uploadprogress').value =0;
        document.getElementById('downloadprogress').value =0;
        stop_progresstimer();
        return;
    }
    if(uploadId ==0 && downloadId ==0) {
        isuploadordownload = false;
        document.getElementById('uploadprogress').value =0;
        document.getElementById('downloadprogress').value =0;
        stop_progresstimer();
        return;
    }
    if(uploadId != 0) {
        sendMsg(CLT_MSG.HTTP_GETPROGRESS,{idtask:uploadId},function(msg){
            if(msg.err !== 0)return;
            upprocess = msg.process;
        });

        if(upprocess <= 0) upprocess = 0;
        document.getElementById('uploadprogress').value = upprocess ;
        document.getElementById('uploadprogress').value += "%";
        if(upprocess == 100) {
            var result;
            sendMsg(CLT_MSG.HTTP_GETRESULT,{idtask:uploadId},function(msg){
                console.log(msg)
                if(msg.err !== 0)return;
                result = msg.error;
                output("上传成功返回信息："+result);
                var data =JSON.parse(result)

                var iframe = window.frameElement.id;
                window.parent.document.getElementById(input_selector).value = data.data.filepath;
                window.parent.document.getElementById(input_selector+'-name').value = data.data.name;
                window.parent.document.getElementById(input_selector+'-file_id').value = data.data.file_id;
                parent.layer.closeAll();
            });

            sendMsg(CLT_MSG.HTTP_CLOSE,{idtask:uploadId},function(msg){
                if(msg.err !== 0 )return;
                output("上传线程已关闭");
            });
            upprocess = 0;
            uploadId  = 0;
            document.getElementById('uploadprogress').value =0;
        }
    }
    if(downloadId != 0) {
        sendMsg(CLT_MSG.HTTP_GETPROGRESS,{idtask:downloadId},function(msg){
            if(msg.err !== 0)return;
            downprocess = msg.process;
        });
        if(downprocess <= 0)
            downprocess = 0;
        document.getElementById('downloadprogress').value = downprocess ;
        document.getElementById('downloadprogress').value += "%";
        if(downprocess == 100) {
            sendMsg(CLT_MSG.HTTP_CLOSE,{idtask:downloadId},function(msg){
                if(msg.err !== 0 )return;
                output("下载线程已关闭");
            });
            downprocess = 0;
            downloadId = 0;
            document.getElementById('downloadprogress').value =0;
        }
    }
    setTimeout("update_progress()", 100);
}
function UploadFile(path_file,input_id,contract_sn) {
    input_selector = input_id.slice(1);
    console.log(contract_sn)
    sendMsg(CLT_MSG.HTTP_UPLOAD,{url:"https://gd.zhmyxt.com/user/assets/webuploader.html?_ajax=1&path="+path_file,filepath:"E:/tp/"+contract_sn+".pdf"},function(msg){
        if(msg.err !== 0)return;
        uploadId = msg.idtask;
        console.log(msg)
        output(uploadId);
        var error;
        sendMsg(CLT_MSG.HTTP_GETRESULT,{idtask:uploadId},function(msg){
            if(msg.err !== 0)return;
            console.log(msg)
            error = msg.error;
            output("上传id="+uploadId+"\n上传错误信息："+error);
            if(error == "")
                start_progresstimer();
        });
    });
}

function DownloadFile()
{
    sendMsg(CLT_MSG.HTTP_DOWNLOAD,{url:"http://flin.cc/Upload/banner/sample/测试.pdf",filepath:"D:/tp/1234.pdf"},function(msg){
        if(msg.err !== 0)return;
        downloadId = msg.idtask;
        output(downloadId);
        //获取上传结果
        var error;
        sendMsg(CLT_MSG.HTTP_GETRESULT,{idtask:downloadId},function(msg){
            if(msg.err !== 0)return;
            error = msg.error;
            output("下载id="+downloadId+"\n下载错误信息："+error);
            //error为空说明上传成功了，开始进度显示
            if(error == "")
                start_progresstimer();
        });
    });
}


